package com.rock.sys.service;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.resource.StringTemplateResourceLoader;

import com.eova.aop.AopContext;
import com.eova.aop.MetaObjectIntercept;
import com.eova.common.Response;
import com.eova.common.utils.xx;
import com.eova.config.EovaConst;
import com.eova.model.MetaObject;
import com.eova.service.sm;
import com.eova.template.common.util.TemplateUtil;
import com.eova.widget.WidgetManager;
import com.eova.widget.WidgetUtil;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

public class RockMetaServUtil {

	/**
	 * 元数据文档文件生成
	 * @param objectCode
	 * @return
	 * @throws Exception 
	 */
	public static File getMetaDocFile(MetaObject object, Object pkValue, AopContext ac) throws Exception {

		// 根据主键获取对象
		Record record = null;
		if(!xx.isEmpty(pkValue))
		 record = Db.use(object.getDs()).findById(object.getView(), object.getPk(), pkValue);
		
		if(record == null){
			record = new Record();
		}
			
		ac.object = object;
		ac.record = record;
		
		MetaObjectIntercept intercept = TemplateUtil.initMetaObjectIntercept(object.getBizIntercept());
		if (intercept != null) {
			String msg = intercept.initDoc(ac);
			if (!xx.isEmpty(msg)) {
				return null;
			}
		}
		
		List<Record> list = new ArrayList();
		list.add(ac.record);

		// 备份Value列，然后将值列转换成Key列
		WidgetUtil.copyValueColumn(list, object.getPk(), object.getFields());
		// 根据表达式将数据中的值翻译成汉字
		WidgetManager.convertValueByExp(ac.ctrl,object, object.getFields(), list);
		
		ac.record = list.get(0);

		Record orc = Db.use(EovaConst.DS_EOVA).findFirst("select * from eova_object where code=?", object.getCode());
		
		//使用beetl模板语言生成doc文档，从文本创建模板
        //此处无法使用jfinal enjoy模板，word转换后的html中有enjoy无法识别的#字符，转换会报错
		StringTemplateResourceLoader resourceLoader = new StringTemplateResourceLoader();
		Configuration cfg = Configuration.defaultConfiguration();
		GroupTemplate gt = new GroupTemplate(resourceLoader, cfg);
		//获取模板
		org.beetl.core.Template t = gt.getTemplate(orc.getStr("dochtml"));
		t.binding("data", ac.record);
		//渲染成html
		String resHtml  = t.render();
		
//		render(new Html2XlsRender("doc", object.getName()+"-"+pkValue, resHtml));
		
		//创建临时文件
		File temp = File.createTempFile(object.getName()+"-"+pkValue, ".docx");
        temp.deleteOnExit();
        BufferedWriter out = new BufferedWriter(new FileWriter(temp));
        out.write(resHtml);
        out.close();
        
		return temp;
		
	}
}
